package com.fw.web.controller.system;

import com.fw.annotation.Log;
import com.fw.constant.Constant;
import com.fw.constant.UserConstants;
import com.fw.core.controller.BaseController;
import com.fw.core.domain.AjaxResult;
import com.fw.core.domain.entity.SysRole;
import com.fw.core.domain.entity.SysUser;
import com.fw.core.domain.model.LoginUser;
import com.fw.core.page.TableDataInfo;
import com.fw.enums.BusinessType;
import com.fw.system.admin.domain.FwUser;
import com.fw.system.admin.domain.SysUserRole;
import com.fw.system.admin.mapper.SysUserRoleMapper;
import com.fw.system.admin.service.IFwUserService;
import com.fw.system.admin.service.ISysPostService;
import com.fw.system.admin.service.ISysRoleService;
import com.fw.system.admin.service.ISysUserService;
import com.fw.utils.ChuangLanSmsUtil;
import com.fw.utils.SecurityUtils;
import com.fw.utils.ServletUtils;
import com.fw.utils.StringUtils;
import com.fw.utils.poi.ExcelUtil;
import com.fw.web.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private IFwUserService fwUserService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 创建后管用户，绑定区县代理角色
     *
     * @param userId 平台用户对象
     * @return AjaxResult
     * @author 姚自强
     * @date 2021/7/28
     */
    @GetMapping("/createSysUser")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult createSysUser(@RequestParam("userId") String userId,@RequestParam("province") String province ,@RequestParam("city") String city,@RequestParam("area") String area){
        FwUser fwUser = fwUserService.getById( userId );
        SysUser sysUser = new SysUser();
        // 找找有没有重复,有的话新创建一个角色即可
        // 默认账号密码, 账号是 proxy_省市区 code 编码(proxy_400102121451}，密码和 app 保持一致即可。
        sysUser.setUserId( Long.valueOf(fwUser.getId()) );
        String proxyName = String.valueOf("proxy_").concat(province).concat(city).concat(area);
        sysUser.setUserName( proxyName );
        sysUser.setNickName( fwUser.getUserName() );
        sysUser.setPhonenumber( fwUser.getPhone() );
        sysUser.setSex( fwUser.getSex()+"" );
        sysUser.setAvatar( fwUser.getHeadImage() );
        sysUser.setPassword(SecurityUtils.encryptPassword(fwUser.getPassWord()));
        sysUser.setCreateTime(new Date());
        userService.insertUser(sysUser);

        ArrayList<SysUserRole> userRoleList = new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId( sysUser.getUserId() );
        //todo 绑定代理角色，写死的，角色id
        sysUserRole.setRoleId(102L);
        userRoleList.add( sysUserRole );
        userRoleMapper.batchUserRole(userRoleList);
        ChuangLanSmsUtil.sendProxyNotice(Constant.ShopInitLogin.SHOP_LOGIN_URL,fwUser.getPhone(),proxyName,fwUser.getPassWord());
        return AjaxResult.success();
    }

}
